<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Python基础小结(一) | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="python,">
  

  <meta name="description" content="最近需要用python做数据分析，决定开始学python，总结一些基础笔记  一、导语 python是解析性语言 python能做什么 大数据分析 自动化运维与自动化测试 web开发：flask、jdango 机器学习 TensorFlow 胶水语言：如混合c++、java编程，能够把其他语法编写的模块连接在一起    Python语言的特点  语法简洁 可跨平台 应用广泛 支持中文 强制可读：">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="Python基础小结(一)">
<meta property="og:url" content="http://blog.poetries.top/2019/12/10/python-base-1/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="最近需要用python做数据分析，决定开始学python，总结一些基础笔记  一、导语 python是解析性语言 python能做什么 大数据分析 自动化运维与自动化测试 web开发：flask、jdango 机器学习 TensorFlow 胶水语言：如混合c++、java编程，能够把其他语法编写的模块连接在一起    Python语言的特点  语法简洁 可跨平台 应用广泛 支持中文 强制可读：">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/107.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/131.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/132.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/133.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/134.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/112.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/109.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/108.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/126.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/113.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/110.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/115.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/114.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/127.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/111.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/181.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python基础小结(一)">
<meta name="twitter:description" content="最近需要用python做数据分析，决定开始学python，总结一些基础笔记  一、导语 python是解析性语言 python能做什么 大数据分析 自动化运维与自动化测试 web开发：flask、jdango 机器学习 TensorFlow 胶水语言：如混合c++、java编程，能够把其他语法编写的模块连接在一起    Python语言的特点  语法简洁 可跨平台 应用广泛 支持中文 强制可读：">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/2019/12/107.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、导语"><span class="toc-text">一、导语</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、基本知识"><span class="toc-text">二、基本知识</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#注释"><span class="toc-text">注释</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#命名"><span class="toc-text">命名</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#保留字"><span class="toc-text">保留字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#input-函数"><span class="toc-text">input()函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#eval-函数"><span class="toc-text">eval()函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#print-函数"><span class="toc-text">print()函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数"><span class="toc-text">函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#文件操作"><span class="toc-text">文件操作</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、基本类型"><span class="toc-text">三、基本类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、序列-元组、字符串、列表"><span class="toc-text">四、序列-元组、字符串、列表</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、运算符"><span class="toc-text">五、运算符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、循环、条件、枚举"><span class="toc-text">六、循环、条件、枚举</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、枚举"><span class="toc-text">七、枚举</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、闭包、模块、函数、变量作用域"><span class="toc-text">八、闭包、模块、函数、变量作用域</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#模块"><span class="toc-text">模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#闭包"><span class="toc-text">闭包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#匿名函数-lambda"><span class="toc-text">匿名函数 lambda</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#map函数"><span class="toc-text">map函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#reduce函数"><span class="toc-text">reduce函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#filter函数"><span class="toc-text">filter函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、装饰器"><span class="toc-text">九、装饰器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十、面向对象"><span class="toc-text">十、面向对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十一、正则表达式"><span class="toc-text">十一、正则表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十二、内建函数"><span class="toc-text">十二、内建函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十三、标准库"><span class="toc-text">十三、标准库</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十四、异常处理"><span class="toc-text">十四、异常处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十五、JSON操作"><span class="toc-text">十五、JSON操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十六、爬虫"><span class="toc-text">十六、爬虫</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十七、常用库"><span class="toc-text">十七、常用库</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#datetime库"><span class="toc-text">datetime库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#random库"><span class="toc-text">random库</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十八、技巧"><span class="toc-text">十八、技巧</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十九、Python知识体系"><span class="toc-text">十九、Python知识体系</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二十、更多参考"><span class="toc-text">二十、更多参考</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-python-base-1" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Python基础小结(一)</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.12.10</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Back-end/">Back-end</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 5.4k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 23分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <blockquote>
<p>最近需要用<code>python</code>做数据分析，决定开始学<code>python</code>，总结一些基础笔记</p>
</blockquote>
<h2 id="一、导语"><a href="#一、导语" class="headerlink" title="一、导语"></a>一、导语</h2><ul>
<li><code>python</code>是解析性语言</li>
<li><code>python</code>能做什么<ul>
<li>大数据分析</li>
<li>自动化运维与自动化测试</li>
<li>web开发：<code>flask</code>、<code>jdango</code></li>
<li>机器学习 <code>TensorFlow</code></li>
<li>胶水语言：如混合c++、java编程，能够把其他语法编写的模块连接在一起</li>
</ul>
</li>
</ul>
<p><strong>Python语言的特点</strong></p>
<ul>
<li>语法简洁</li>
<li>可跨平台</li>
<li>应用广泛</li>
<li>支持中文</li>
<li>强制可读：通过强制缩进体现语句间的逻辑关系提高了程序的可读性</li>
<li>模式多样：语法层面同时支持面向过程和面向对象两种编程方式</li>
<li>粘性扩展：通过接口和函数集成其他语言编写的代码</li>
<li>开源理念</li>
<li>库类丰富</li>
</ul>
<p><strong>Python语言开发环境配置</strong></p>
<ul>
<li><code>Python</code>解释器</li>
<li><code>IDLE</code>开发环境</li>
<li>交互式启动</li>
<li>文件式启动</li>
<li><code>Python</code>语言集成开发环境——<code>PyCharm</code></li>
</ul>
<h2 id="二、基本知识"><a href="#二、基本知识" class="headerlink" title="二、基本知识"></a>二、基本知识</h2><h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><ul>
<li>注释是辅助性文字，不被执行</li>
<li>单行注释：以<code>#</code>开头</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">#这是注释</span><br></pre></td></tr></table></figure>
<blockquote>
<p>多行注释：以<code>&#39;&#39;&#39;</code>(3个单引号)开头和结尾</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&apos;&apos;&apos;</span><br><span class="line">这是注释</span><br><span class="line">这也是注释</span><br><span class="line">这还是注释</span><br><span class="line">&apos;&apos;&apos;</span><br></pre></td></tr></table></figure>
<h3 id="命名"><a href="#命名" class="headerlink" title="命名"></a>命名</h3><ul>
<li>命名是为变量关联标识符的过程，用于确保程序元素的唯一性</li>
<li>标识符由字母、数字、下划线（和汉字）等字符及其组合构成</li>
<li>标识符的首字符不能是数字 ，且中间不能出现空格</li>
<li>标识符对大小写敏感</li>
</ul>
<h3 id="保留字"><a href="#保留字" class="headerlink" title="保留字"></a>保留字</h3><ul>
<li>保留字（<code>Keyword</code>）也被称为关键字，是被编程语言内部定义并保留使用的标识符</li>
<li><code>Python</code> 的标准库提供了一个 <code>keyword</code> 模块，可以输出当前版本的所有关键字：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; import keyword</span><br><span class="line">&gt;&gt;&gt; ls=keyword.kwlist</span><br><span class="line">&gt;&gt;&gt; ls</span><br><span class="line">&gt;&gt;&gt;len(ls)</span><br><span class="line">33</span><br></pre></td></tr></table></figure>
<p><strong>Python 3 有33个保留字</strong></p>
<ul>
<li><code>True</code></li>
<li><code>False</code></li>
<li><code>None</code></li>
<li><code>and</code></li>
<li><code>as</code></li>
<li><code>assert</code></li>
<li><code>break</code></li>
<li><code>class</code></li>
<li><code>continue</code></li>
<li><code>def</code></li>
<li><code>del</code></li>
<li><code>elif</code></li>
<li><code>else</code></li>
<li><code>except</code></li>
<li><code>finally</code></li>
<li><code>for</code></li>
<li><code>from</code></li>
<li><code>global</code></li>
<li><code>if</code></li>
<li><code>import</code></li>
<li><code>in</code></li>
<li><code>is</code></li>
<li><code>lambda</code></li>
<li><code>nonlocal</code></li>
<li><code>not</code></li>
<li><code>or</code></li>
<li><code>pass</code></li>
<li><code>raise</code></li>
<li><code>return</code></li>
<li><code>try</code></li>
<li><code>while</code></li>
<li><code>with</code></li>
<li><code>yield</code></li>
</ul>
<h3 id="input-函数"><a href="#input-函数" class="headerlink" title="input()函数"></a>input()函数</h3><ul>
<li>使用<code>input()</code>函数从控制台获得用户输入</li>
<li><code>input()</code>函数以字符串类型返回结果</li>
</ul>
<h3 id="eval-函数"><a href="#eval-函数" class="headerlink" title="eval()函数"></a>eval()函数</h3><ul>
<li><code>eval(&lt;字符串&gt;)</code>函数的作用是间输入的字符串变成Python语句并执行</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">x=eval(input(&quot;请输入：&quot;))</span><br></pre></td></tr></table></figure>
<h3 id="print-函数"><a href="#print-函数" class="headerlink" title="print()函数"></a>print()函数</h3><ul>
<li><code>print()</code>函数可以输出字符信息，也可以用字符的形式输出变量</li>
<li>输出字符信息时，可以直接将待输出内容传递给<code>print()</code>函数</li>
<li>输出变量值时，<code>print()</code>函数用槽格式和过<code>format()</code>方法将变量和字符串结合到一起输出</li>
</ul>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><ul>
<li>函数可以理解为对一组表达特定功能表达式的封装，将特定功能代码编写在一个函数里，使程序模块化更好，便于阅读和复用</li>
<li>可通过保留字<code>def</code>自定义函数</li>
</ul>
<h3 id="文件操作"><a href="#文件操作" class="headerlink" title="文件操作"></a>文件操作</h3><p><img src="https://poetries1.gitee.io/img-repo/2019/12/107.png" alt></p>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 使用with操作文件</span></span><br><span class="line"><span class="keyword">with</span> open(os.path.dirname(__file__) + <span class="string">'/blog.text'</span>,<span class="string">'w'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(json.dumps(data))</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/131.png" alt="路径操作模块"><br><img src="https://poetries1.gitee.io/img-repo/2019/12/132.png" alt="图片"><br><img src="https://poetries1.gitee.io/img-repo/2019/12/133.png" alt="Excel"><br><img src="https://poetries1.gitee.io/img-repo/2019/12/134.png" alt="文本其他"></p>
<h2 id="三、基本类型"><a href="#三、基本类型" class="headerlink" title="三、基本类型"></a>三、基本类型</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/12/112.png" alt="python基本数据类型"></p>
<p><strong>类型判断两个方式</strong></p>
<ul>
<li><code>type</code> 判断基本类型 如 <code>type(10) == int</code> 不推荐</li>
<li><p><code>isinstance(值,类型)</code> 或者 <code>isinstance(值,(int,float,str))</code> 三种中任意一种</p>
<ul>
<li>例 <code>isinstance(1,int)</code></li>
</ul>
</li>
<li><p><code>Number</code></p>
<ul>
<li><code>int</code></li>
<li><code>float</code></li>
<li><code>complex</code> 复数<ul>
<li>如<code>36j</code></li>
</ul>
</li>
</ul>
</li>
<li><code>Bool</code><ul>
<li><code>bool(&#39;&#39;)/bool([])/bool({})/bool(0)/bool(None)</code></li>
<li>都是转化为<code>False</code></li>
</ul>
</li>
<li>字符串<code>str</code> （序列）<ul>
<li>单引号</li>
<li>双引号</li>
<li>三引号(可以换行写多个字符串和ES6的反引号类似)</li>
<li>在字符串前面加一个<code>r</code>，这个字符串就不是一个普通字符串，而是一个原始字符串会原样输出 <code>print(r&#39;\n88fafa&#39;)</code> 此时<code>\n</code>不会转译</li>
</ul>
</li>
<li><code>list</code> 列表 （序列）</li>
<li><code>tuple</code> 元组 （序列）</li>
<li>集合<code>set</code>(无序，没有索引，不能切片，元素唯一，不能重复,只有<code>value</code>，没<code>key</code>) <code>{}</code> 如 <code>{1,2,3,4}</code><ul>
<li><code>1 in {1,2,3}</code></li>
<li><code>1 not in {1,2,3,4}</code></li>
<li>两个集合插集<code>{1,2,3} - {4,5}</code></li>
<li>两个集合求交集 <code>{1,2,3,4} &amp; {2,3}</code></li>
<li>并集 <code>{1,2,3,4,5,6} | {3,4,7}</code></li>
<li>定义一个空的集合 <code>set()</code></li>
</ul>
</li>
<li>字典<code>dict</code>（有<code>key</code>无<code>value</code>，不同于集合只有<code>value</code>）<ul>
<li>很多<code>key-value</code>组成,不能够有相同的键，</li>
<li><code>key</code>键不可变类型，可以是<code>int/str/tuple</code> </li>
<li><code>value</code>可以是：<code>int/str/float/list/set/dict</code></li>
<li>定义一个空的字典 <code>{}</code></li>
</ul>
</li>
</ul>
<blockquote>
<p>两个整型相除得到整型 type(1//2) ==&gt;int 整除会保留整数</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">// 二进制</span><br><span class="line">0b10012</span><br><span class="line"></span><br><span class="line">// 八进制</span><br><span class="line">0o101</span><br><span class="line"></span><br><span class="line">// 16进制</span><br><span class="line">0x10</span><br><span class="line"></span><br><span class="line">// 10进制转二进制</span><br><span class="line">bin(10)</span><br><span class="line"></span><br><span class="line">// 八进制转二进制</span><br><span class="line">bin(o09012)</span><br><span class="line"></span><br><span class="line">// 八进制、二进制转十进制</span><br><span class="line">int(0b1000)</span><br><span class="line"></span><br><span class="line">// 十进制转16进制</span><br><span class="line">hex(88891)</span><br><span class="line"></span><br><span class="line">// 八进制转化</span><br><span class="line">oct(0b100)</span><br></pre></td></tr></table></figure>
<p><strong>转译字符</strong></p>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line">\n 换行</span><br><span class="line">\t 横向制表符</span><br></pre></td></tr></table></figure>
<p><strong>内置的字符串处理函数</strong></p>
<table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>len(&#39;x&#39;)</code></td>
<td>返回字符串<code>x</code>的长度，也可返回其他组合数据类型元素个数</td>
</tr>
<tr>
<td><code>str(&#39;x&#39;)</code></td>
<td>返回任意类型<code>x</code>所对应的字符串形式</td>
</tr>
<tr>
<td><code>chr(x)</code></td>
<td>返回<code>Unicode</code>编码<code>x</code>对应的单字符</td>
</tr>
<tr>
<td><code>ord(&#39;x&#39;)</code></td>
<td>返回单字符表示的<code>Unicode</code>编码</td>
</tr>
<tr>
<td><code>hex(x)</code></td>
<td>返回整数<code>x</code>对应十六进制数的小写形式字符串</td>
</tr>
<tr>
<td><code>oct(x)</code></td>
<td>返回整数<code>x</code>对应八进制数的小写形式字符串</td>
</tr>
</tbody>
</table>
<p><strong>内置的字符串处理方法（共43个，常用16个）</strong></p>
<ul>
<li>在<code>Python</code>解释器内部，所有数据类型都采用面向对象的方式实现，封装为一个类</li>
<li>字符串是一个类，具有类似<code>&lt;a&gt;.&lt;b&gt;()</code>形式的字符串处理函数，称为方法</li>
</ul>
<table>
<thead>
<tr>
<th>方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>str.lower()</code></td>
<td>返回字符串<code>str</code>的副本，全部字符小写</td>
</tr>
<tr>
<td><code>str.upper()</code></td>
<td>返回字符串<code>str</code>的副本，全部字符大写</td>
</tr>
<tr>
<td><code>str.islower()</code></td>
<td>当str所有字符都是小写时，返回<code>Ture</code>，否则返回<code>False</code></td>
</tr>
<tr>
<td><code>str.isprintable()</code></td>
<td>当str所有字符都是可打印的，返回<code>Ture</code>，否则返回<code>False</code></td>
</tr>
<tr>
<td><code>str.isnumeric()</code></td>
<td>当str所有字符都是数字时，返回<code>Ture</code>，否则返回<code>False</code></td>
</tr>
<tr>
<td><code>str.isspace()</code></td>
<td>当str所有字符都是空格，返回<code>Ture</code>，否则返回<code>Flase</code></td>
</tr>
<tr>
<td><code>str.endswith(suffix[,start[,end]])</code></td>
<td><code>str[start:end]</code>以<code>suffix</code>结尾返回<code>Ture</code>，否则返回<code>Flase</code></td>
</tr>
<tr>
<td><code>str.srartswith(prefix[,start[,end]])</code></td>
<td><code>str[start:end]</code>以<code>prefix</code>开始返回<code>Ture</code>，否则返回<code>Flase</code></td>
</tr>
<tr>
<td><code>str.split(sep=None,maxsplit=-1)</code></td>
<td>返回一个列表，由<code>str</code>根据<code>sep</code>被分割的部分构成</td>
</tr>
<tr>
<td><code>str.count(sub[,start[,end]]</code></td>
<td>返回<code>str[start:end]</code>中<code>sub</code>子串出现的次数</td>
</tr>
<tr>
<td><code>str.replace(old,new[,count])</code></td>
<td>返回字符串<code>str</code>的副本，所有<code>old</code>子串被替换为<code>new</code>，如果<code>count</code>给出，则前<code>count</code>次<code>old</code>出现被替换</td>
</tr>
<tr>
<td><code>str.center(width[,fillchar])</code></td>
<td>字符串居中函数</td>
</tr>
<tr>
<td><code>str.strip([chars])</code></td>
<td>返回字符串<code>str</code>的副本，在其左侧和右侧去掉<code>chars</code>中列出的字符</td>
</tr>
<tr>
<td><code>str.zfill(width)</code></td>
<td>返回字符串<code>str</code>副本，长度为<code>width</code>。不足部分在其左侧添加<code>0</code></td>
</tr>
<tr>
<td><code>str.format()</code></td>
<td>返回字符串<code>str</code>的一种排版格式</td>
</tr>
<tr>
<td><code>str.join(iterable)</code></td>
<td>返回一个新字符串，由组合数据类型<code>iterable</code>变量的每个元素组成，元素间用<code>str</code>分隔</td>
</tr>
</tbody>
</table>
<h2 id="四、序列-元组、字符串、列表"><a href="#四、序列-元组、字符串、列表" class="headerlink" title="四、序列-元组、字符串、列表"></a>四、序列-元组、字符串、列表</h2><p><strong>序列共性</strong></p>
<ul>
<li>切片</li>
<li>序号</li>
<li><code>in</code>判断符 <code>2 in [1,2,3]</code> <code>2 not in [1,2,3]</code></li>
<li><code>len()</code></li>
<li><code>max(list)</code></li>
<li><code>min(list)</code></li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/109.png" alt="序列"></p>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/108.png" alt="序列基本操作"></p>
<p><strong>可变类型</strong></p>
<ul>
<li><code>list</code> 需要动态改变，就用列表</li>
<li><code>dict</code></li>
<li><code>set</code></li>
</ul>
<p><strong>不可变类型</strong></p>
<ul>
<li><code>str</code></li>
<li><code>tuple</code> 定义之后不可变，安全性较高</li>
<li><code>int</code></li>
</ul>
<p><strong>字符串基本操作</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">// +号运算</span><br><span class="line">str1 = &apos;hell&apos;</span><br><span class="line">str2 = &apos;world&apos;</span><br><span class="line">str = str1 + str2</span><br><span class="line"></span><br><span class="line">// 乘法运算 </span><br><span class="line">str1*3 // 重复3次</span><br><span class="line"></span><br><span class="line">// 切片</span><br><span class="line">str1[1:2]</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">// 赋值操作</span><br><span class="line">year,month,day = (2019,10,12)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>如果只有一个元素，应该这样表示元组 <code>(1,)</code>,一个元素都没有的元组 <code>type( () )</code></p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/126.png" alt="python类型转换"></p>
<h2 id="五、运算符"><a href="#五、运算符" class="headerlink" title="五、运算符"></a>五、运算符</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/12/113.png" alt="python运算符"></p>
<p><strong>列表元组都可以比较</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>) &gt; (<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>) <span class="comment">// 两两比较第一个、第二个...数字</span></span><br></pre></td></tr></table></figure>
<p><strong>字典的成员运算符</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 只针对key</span></span><br><span class="line"><span class="string">'a'</span> <span class="keyword">in</span> &#123;<span class="string">'a'</span>: <span class="string">'1'</span>&#125; <span class="comment">// True</span></span><br></pre></td></tr></table></figure>
<p><strong>身份运算符</strong></p>
<ul>
<li><code>is</code> 两个取值相等才会返回True  <code>&#39;1&#39; is &#39;1&#39; // True</code></li>
<li><code>is not</code> 不等</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 关系运算符比较的是两个值是否相等 如</span></span><br><span class="line"><span class="number">1</span> == <span class="number">1.0</span> <span class="comment">// True</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// is比较的是两个变量内存地址是否相等 id(值) 获取内存地址</span></span><br><span class="line"><span class="number">1</span> is <span class="number">1.0</span> <span class="comment">// False</span></span><br></pre></td></tr></table></figure>
<p><strong>对象的三个特征</strong></p>
<ul>
<li><code>id</code>(身份) =&gt; <code>is</code>判断</li>
<li><code>value</code> =&gt; <code>==</code> 判断</li>
<li><code>type</code> =&gt; <code>isinstance</code> 判断</li>
</ul>
<p><strong>位运算符</strong></p>
<blockquote>
<p>把数字当二进制进行运算。把非二进制转化为二进制才计算</p>
</blockquote>
<ul>
<li><code>&amp;</code> 按位与</li>
<li><code>|</code> 按位或</li>
<li><code>^</code> 按位异或</li>
<li><code>~</code>按位取反</li>
<li><code>&lt;&lt;</code> 左移动</li>
<li><code>&gt;&gt;</code> 右移动</li>
</ul>
<h2 id="六、循环、条件、枚举"><a href="#六、循环、条件、枚举" class="headerlink" title="六、循环、条件、枚举"></a>六、循环、条件、枚举</h2><ul>
<li><code>if else</code></li>
<li><code>while</code></li>
<li><code>for in</code></li>
</ul>
<p><strong>range</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 等同于</span></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;len;i++)&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// range</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>,<span class="number">10</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2是步长</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>,<span class="number">10</span>,<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 取出1，3，5，7</span></span><br><span class="line">a = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>,len(a),<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//切片写法</span></span><br><span class="line">a[<span class="number">0</span>:len(a):<span class="number">2</span>]</span><br></pre></td></tr></table></figure>
<h2 id="七、枚举"><a href="#七、枚举" class="headerlink" title="七、枚举"></a>七、枚举</h2><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">枚举</span></span><br><span class="line"><span class="string">'''</span> </span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> enum <span class="keyword">import</span> Enum</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">VIP</span><span class="params">(Enum)</span>:</span></span><br><span class="line">  <span class="comment"># 值可以相同 但是py会把第二个设置别名</span></span><br><span class="line">  yellow = <span class="number">1</span></span><br><span class="line">  green = <span class="number">2</span></span><br><span class="line">  red = <span class="number">3</span></span><br><span class="line">  black = <span class="number">4</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 枚举不能被修改</span></span><br><span class="line"><span class="comment"># VIP.red = 10</span></span><br><span class="line">print(VIP.yellow)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取枚举值</span></span><br><span class="line">print(VIP.yellow.value)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取枚举标签</span></span><br><span class="line">print(VIP.yellow.name)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 根据名称获取枚举类</span></span><br><span class="line">print(VIP[<span class="string">'red'</span>]) <span class="comment"># VIP.red</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 枚举遍历 获取每个成员</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> VIP:</span><br><span class="line">  print(i)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> v <span class="keyword">in</span> VIP.__members__.items():</span><br><span class="line">  print(v)</span><br><span class="line"></span><br><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">('yellow', &lt;VIP.yellow: 1&gt;)</span></span><br><span class="line"><span class="string">('green', &lt;VIP.green: 2&gt;)</span></span><br><span class="line"><span class="string">('red', &lt;VIP.red: 3&gt;)</span></span><br><span class="line"><span class="string">('black', &lt;VIP.black: 4&gt;)</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 成员之间进行比较 不持续大小比较</span></span><br><span class="line">res = VIP.red == VIP.black</span><br><span class="line">print(res) <span class="comment"># False</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 身份比较</span></span><br><span class="line">print(VIP.red <span class="keyword">is</span> VIP.red)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 枚举类型转换</span></span><br><span class="line">print(VIP(<span class="number">1</span>)) <span class="comment"># VIP.yellow</span></span><br></pre></td></tr></table></figure>
<h2 id="八、闭包、模块、函数、变量作用域"><a href="#八、闭包、模块、函数、变量作用域" class="headerlink" title="八、闭包、模块、函数、变量作用域"></a>八、闭包、模块、函数、变量作用域</h2><h3 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h3><p><img src="https://poetries1.gitee.io/img-repo/2019/12/110.png" alt="模块"></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在文件中写`__init__.py` 只是标注这是一个包 可以什么都不用写</span></span><br></pre></td></tr></table></figure>
<p><strong>导入模块重新命名</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import test as t</span><br></pre></td></tr></table></figure>
<p><strong>函数</strong></p>
<blockquote>
<p>函数内部没有<code>return</code> 返回的结果就是<code>None</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 函数可以返回多个值</span></span><br><span class="line">def test():</span><br><span class="line">  <span class="keyword">return</span> x, y,z</span><br><span class="line">  </span><br><span class="line"><span class="comment">// 接收返回的值</span></span><br><span class="line">x,y,z = test()  <span class="comment">// 其实就是返回了一个元组类型</span></span><br></pre></td></tr></table></figure>
<h3 id="闭包"><a href="#闭包" class="headerlink" title="闭包"></a>闭包</h3><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">闭包 = 函数+环境变量（在函数外部）</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">()</span>:</span></span><br><span class="line">  num = <span class="number">10</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">fun</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> num * x</span><br><span class="line">  <span class="keyword">return</span> fun</span><br><span class="line"></span><br><span class="line">f = test()</span><br><span class="line">print(f(<span class="number">10</span>))</span><br><span class="line"></span><br><span class="line">origin = <span class="number">0</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">go</span><span class="params">(step)</span>:</span></span><br><span class="line">  <span class="keyword">global</span> origin </span><br><span class="line">  new_pos = step + origin </span><br><span class="line">  origin = new_pos</span><br><span class="line">  <span class="keyword">return</span> new_pos</span><br><span class="line"></span><br><span class="line">print(go(<span class="number">1</span>))</span><br><span class="line">print(go(<span class="number">2</span>))</span><br><span class="line">print(go(<span class="number">3</span>))</span><br></pre></td></tr></table></figure>
<h3 id="匿名函数-lambda"><a href="#匿名函数-lambda" class="headerlink" title="匿名函数 lambda"></a>匿名函数 lambda</h3><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">函数式编程：匿名函数 lambda</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(x,y)</span>:</span></span><br><span class="line">  <span class="keyword">return</span> x + y </span><br><span class="line"></span><br><span class="line">add(<span class="number">1</span>,<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 匿名函数定义</span></span><br><span class="line">f = <span class="keyword">lambda</span> x,y: x+y</span><br><span class="line"></span><br><span class="line">print(f(<span class="number">1</span>,<span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">arr = [&#123;<span class="string">'key'</span>: <span class="string">'poetries'</span>,<span class="string">'value'</span>: <span class="number">100</span>&#125;,&#123;<span class="string">'key'</span>: <span class="string">'jing'</span>,<span class="string">'value'</span>: <span class="number">10</span>&#125;]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 处理键值对</span></span><br><span class="line">res = map(<span class="keyword">lambda</span> item: &#123;<span class="string">'name'</span>: item[<span class="string">'key'</span>],<span class="string">'score'</span>: item[<span class="string">'value'</span>]&#125;, arr)</span><br><span class="line"></span><br><span class="line">print(list(res))</span><br></pre></td></tr></table></figure>
<h3 id="map函数"><a href="#map函数" class="headerlink" title="map函数"></a>map函数</h3><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">map函数</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line">arr2 = [<span class="number">10</span>,<span class="number">12</span>,<span class="number">14</span>,<span class="number">16</span>,<span class="number">12</span>,<span class="number">14</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 列表推导式</span></span><br><span class="line">a = [i*i <span class="keyword">for</span> i <span class="keyword">in</span> arr ]</span><br><span class="line"></span><br><span class="line"><span class="comment"># print(a)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># map函数</span></span><br><span class="line">b = map(<span class="keyword">lambda</span> x: x*x,arr)</span><br><span class="line">print(list(b))</span><br><span class="line"></span><br><span class="line">c = map(<span class="keyword">lambda</span> x,y: x*x + y,arr,arr2) <span class="comment"># 可以传多个list，个数要相同</span></span><br><span class="line">print(list(c))</span><br></pre></td></tr></table></figure>
<h3 id="reduce函数"><a href="#reduce函数" class="headerlink" title="reduce函数"></a>reduce函数</h3><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">reduce函数</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line"></span><br><span class="line">arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 连续调用lambda</span></span><br><span class="line">r = reduce(<span class="keyword">lambda</span> x,y:x+y,arr)</span><br><span class="line"></span><br><span class="line">print(r)</span><br></pre></td></tr></table></figure>
<h3 id="filter函数"><a href="#filter函数" class="headerlink" title="filter函数"></a>filter函数</h3><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">filter函数</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line">arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="literal">False</span>,<span class="string">''</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 过滤空字符串</span></span><br><span class="line">res = filter(<span class="keyword">lambda</span> x: <span class="keyword">not</span> <span class="keyword">not</span> x,arr)</span><br><span class="line"></span><br><span class="line">print(list(res)) <span class="comment"># [1,2,3,4,5,6,7]</span></span><br></pre></td></tr></table></figure>
<h2 id="九、装饰器"><a href="#九、装饰器" class="headerlink" title="九、装饰器"></a>九、装饰器</h2><figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">装饰器:特性、注解</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> time </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">decorator1</span><span class="params">(func)</span>:</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(name)</span>:</span></span><br><span class="line">    print(time.time())</span><br><span class="line">    func(name)</span><br><span class="line">  <span class="keyword">return</span> wrapper</span><br><span class="line"></span><br><span class="line"><span class="meta">@decorator1 </span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f1</span><span class="params">(name)</span>:</span></span><br><span class="line">  print(<span class="string">'this is a func'</span>,name)</span><br><span class="line"></span><br><span class="line"><span class="comment"># f1('poetries')</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">decorator2</span><span class="params">(func)</span>:</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(*args,**kw)</span>:</span></span><br><span class="line">    print(time.time())</span><br><span class="line">    print(args,<span class="string">'args'</span>)</span><br><span class="line">    print(kw,<span class="string">'kw'</span>)</span><br><span class="line">    func(*args,**kw)</span><br><span class="line">  <span class="keyword">return</span> wrapper</span><br><span class="line"></span><br><span class="line"><span class="meta">@decorator2</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f2</span><span class="params">(p1,p2)</span>:</span></span><br><span class="line">  print(<span class="string">'this is a func'</span>,p1,p2)</span><br><span class="line"></span><br><span class="line">f2(<span class="string">'静观流叶'</span>,<span class="string">'1'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="十、面向对象"><a href="#十、面向对象" class="headerlink" title="十、面向对象"></a>十、面向对象</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/12/115.png" alt="类"></p>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">面向对象</span></span><br><span class="line"><span class="string">类=面向对象</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">行为、特征</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">类最基本的作用封装代码</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line">__author__ = <span class="string">'poetries'</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span><span class="params">(Human)</span>:</span></span><br><span class="line">  <span class="comment"># 类变量 静态属性</span></span><br><span class="line">  author = <span class="string">'poetry'</span> </span><br><span class="line">  SUM = <span class="number">10</span></span><br><span class="line">  num = <span class="number">999</span></span><br><span class="line">  score = <span class="number">98</span></span><br><span class="line">  text = <span class="string">'小明今年'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,name,age)</span>:</span></span><br><span class="line">    <span class="comment"># 构造函数 初始化对象属性</span></span><br><span class="line">    <span class="comment"># 成员可见性 __外部不能访问</span></span><br><span class="line">    self.__name = name </span><br><span class="line">    self.__age = age </span><br><span class="line"></span><br><span class="line">  <span class="comment"># 实例方法 第一个参数默认是self</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">getAge</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="comment"># 实例中可调用类变量</span></span><br><span class="line">    <span class="comment"># print(self.author)</span></span><br><span class="line">    <span class="keyword">return</span> self.__getText() + str(self.__age)</span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">getName</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> self.__name</span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">setName</span><span class="params">(self,name)</span>:</span></span><br><span class="line">    self.__name = name</span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 私有方法，外部不可以访问</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__getText</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> self.text</span><br><span class="line"></span><br><span class="line">  <span class="comment"># 静态方法</span></span><br><span class="line">  <span class="comment"># 没有self</span></span><br><span class="line">  <span class="comment"># 实例和类都可以调用</span></span><br><span class="line"><span class="meta">  @staticmethod</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="comment"># 内部可以访问类变量</span></span><br><span class="line">    print(<span class="string">'静态方法'</span>,Student.SUM)</span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 类方法 操作和类相关的</span></span><br><span class="line">  <span class="comment"># cls代表student这个类</span></span><br><span class="line">  <span class="comment"># 使用方式 student.testd()</span></span><br><span class="line">  <span class="comment"># 实例和类都可以调用，不要使用实例调用</span></span><br><span class="line">  <span class="comment"># 推荐使用类方法代替静态方法</span></span><br><span class="line"><span class="meta">  @classmethod</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">testd</span><span class="params">(cls)</span>:</span></span><br><span class="line">    print(<span class="string">'classMethod'</span>)</span><br><span class="line">  </span><br><span class="line">stu = Student(<span class="string">'poetries'</span>,<span class="number">22</span>)</span><br><span class="line"></span><br><span class="line">print(stu.getAge())</span><br><span class="line"></span><br><span class="line"><span class="comment"># 修改内部变量值，通过内部定义一个方法，可以在内部进行判断，起到保护作用</span></span><br><span class="line">stu.setName(<span class="string">'静观流叶'</span>)</span><br><span class="line"></span><br><span class="line">print(stu.getName())</span><br><span class="line"></span><br><span class="line"><span class="comment"># print(Student.author)</span></span><br><span class="line"><span class="comment"># print(Student.__dict__)</span></span><br><span class="line"><span class="comment"># print(Student.test())</span></span><br></pre></td></tr></table></figure>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">继承</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Human</span><span class="params">(object)</span>:</span></span><br><span class="line">  num =<span class="number">10</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,name,age)</span>:</span></span><br><span class="line">    self.__name = name</span><br><span class="line">    self.__age = age </span><br><span class="line">    </span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">getName</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> self.__name</span><br><span class="line"></span><br><span class="line"><span class="comment"># 继承父类Human</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span><span class="params">(Human)</span>:</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,school,name,age)</span>:</span></span><br><span class="line">    self.school = school</span><br><span class="line">    <span class="comment"># 子类调用父类构造函数 </span></span><br><span class="line">    <span class="comment"># 方式1</span></span><br><span class="line">    <span class="comment"># Human.__init__(self,name,age)</span></span><br><span class="line">    <span class="comment"># 方式2 推荐super</span></span><br><span class="line">    super(Student,self).__init__(name,age)</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">getInfo</span><span class="params">(self)</span>:</span> </span><br><span class="line">    <span class="keyword">return</span> self.getName() + self.school</span><br><span class="line"></span><br><span class="line">stu = Student(<span class="string">'中山大学'</span>,<span class="string">'poetry'</span>,<span class="number">22</span>)</span><br><span class="line">print(stu.getInfo())</span><br></pre></td></tr></table></figure>
<h2 id="十一、正则表达式"><a href="#十一、正则表达式" class="headerlink" title="十一、正则表达式"></a>十一、正则表达式</h2><blockquote>
<p>是一个特殊的字符序列，一个字符串是否与我们所设定的这样的字符序列相匹配</p>
</blockquote>
<p>库re</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//替换非数字的</span></span><br><span class="line"> s = re.sub(<span class="string">'\D'</span>,<span class="string">''</span>,<span class="string">'9fafjla9dfaldfah-dfal+++)@#--9912'</span>)</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="comment">// 例子 传递函数 根据匹配结果替换操作</span></span><br><span class="line">def convert(value):</span><br><span class="line">  match = value.group()</span><br><span class="line">  <span class="keyword">return</span> <span class="string">'!!'</span> + match</span><br><span class="line"></span><br><span class="line">re.sub(<span class="string">'#c'</span>, convert, <span class="string">'pythonc#fda'</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// findall 可以加上第三个参数模式re.I忽略大小写</span></span><br><span class="line"><span class="comment">// re.S 改变.的匹配行为，可以匹配换行符`/n`  </span></span><br><span class="line"><span class="comment">// 返回 ['99999']</span></span><br><span class="line">re.findall(<span class="string">'\d+'</span>,<span class="string">'kfdafd99999fa'</span>,re.I | re.S)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 匹配仅仅是对前面那个字符起作用</span></span><br><span class="line"><span class="comment">// n匹配0次或者1次</span></span><br><span class="line">re.findall(<span class="string">'python?'</span>, <span class="string">'pythonnn'</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><code>re.match</code> 没有找到匹配的，将会返回<code>None</code></li>
<li><code>re.search</code> 直到搜索到</li>
<li><code>re.sub</code> 替换</li>
<li><code>re.findall</code> 推荐 返回一个列表</li>
</ul>
<h2 id="十二、内建函数"><a href="#十二、内建函数" class="headerlink" title="十二、内建函数"></a>十二、内建函数</h2><p><a href="https://docs.python.org/3/library/functions.html" target="_blank" rel="noopener">https://docs.python.org/3/library/functions.html</a></p>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/114.png" alt="内建函数"></p>
<h2 id="十三、标准库"><a href="#十三、标准库" class="headerlink" title="十三、标准库"></a>十三、标准库</h2><p>常用模块</p>
<ul>
<li>文字处理 re</li>
<li>日期类型 time、datetime</li>
<li>随机数、数学类型  math、random</li>
<li>文件和目录访问 pathlib os.path</li>
<li>数据压缩 tarfile</li>
<li>通用操作系统 os、logging、argparse</li>
<li>多线程 threading、queue</li>
<li>网络数据处理 base64 json urllib</li>
<li>结构化标记处理工具 html xml</li>
<li>调试工具 timeit</li>
<li>软件包发布 venv</li>
<li>运行服务的 <strong>main</strong></li>
</ul>
<h2 id="十四、异常处理"><a href="#十四、异常处理" class="headerlink" title="十四、异常处理"></a>十四、异常处理</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/12/127.png" alt="python异常类型"></p>
<blockquote>
<p><code>try-except</code>语句</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">try:</span><br><span class="line">    &lt;语句块1&gt;</span><br><span class="line">except &lt;异常类型&gt;:</span><br><span class="line">    &lt;语句块2&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>try-except语句可以支持多个except语句</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">try:</span><br><span class="line">    &lt;语句块1&gt;</span><br><span class="line">except &lt;异常类型1&gt;：</span><br><span class="line">    &lt;语句块2&gt;</span><br><span class="line">...</span><br><span class="line">except &lt;异常类型N&gt;:</span><br><span class="line">    &lt;语句块N+1&gt;</span><br><span class="line">except &lt;异常类型N+!&gt;:</span><br><span class="line">    &lt;语句块N+2&gt;</span><br></pre></td></tr></table></figure>
<h2 id="十五、JSON操作"><a href="#十五、JSON操作" class="headerlink" title="十五、JSON操作"></a>十五、JSON操作</h2><ul>
<li><code>json</code>库主要包括两类函数，操作类函数和解析类函数</li>
<li>操作类函数主要完成外部<code>JSON</code>格式和程序内部数据类型之间的转换功能<br>解析类函数主要用于解析键值对内容</li>
<li><code>json</code>格式包括对象和数组</li>
<li>对象用大括号(<code>{}</code>)表示，对应键值对的组合关系（被<code>json</code>库解析为字典）</li>
<li>数组用中括号(<code>{}</code>)表示，对应键值对的对等关系（被<code>json</code>库解析为列表）</li>
</ul>
<p><strong>json库解析</strong></p>
<ul>
<li><code>json</code>库包含编码（<code>encoding</code>）和解码（<code>decoding</code>）两个过程<br>编码将<code>Python</code>数据类型变换成JSON格式</li>
<li>解码是从<code>JSON</code>格式中解析数据对应到<code>Python</code>数据类型的过程<br><code>json</code>库的操作类函数</li>
</ul>
<table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>json.dumps(obj,sort_keys=Flase,indent=None)</code></td>
<td>将Python的数据类型转换为<code>JSON</code>格式，编码过程</td>
</tr>
<tr>
<td><code>json.loads(string)</code></td>
<td>将<code>JSON</code>格式字符串转换为Python的数据类型，解码过程</td>
</tr>
<tr>
<td><code>json.dump(obj,fp，sort_keys=Flase,indent=None)</code></td>
<td>与<code>dumps()</code>功能一致，输出到文件<code>fp</code></td>
</tr>
<tr>
<td><code>json.load(fp)</code></td>
<td>与<code>loads()</code>功能一致，从文件<code>fp</code>读入</td>
</tr>
</tbody>
</table>
<ul>
<li><code>json.dumps()</code>中的<code>obj</code>可以是<code>Python</code>的列表或字典类型，当输入字典类型时，<code>dumps()</code>函数将其变为<code>JSON</code>格式字符串</li>
<li>默认生成的字符串是顺序存放的，<code>sort_keys</code>可以对字典元素按照<code>key</code>进行排序控制输出结果</li>
<li><code>indent</code>参数用于增加数据缩进，使得生成的<code>JSON</code>格式字符串更具可读性</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"></span><br><span class="line"><span class="comment">// 反序列化</span></span><br><span class="line">str = <span class="string">"&#123;'name': 'poetries'&#125;"</span></span><br><span class="line">json.loads(str)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 序列化</span></span><br><span class="line">json.dumps([&#123;<span class="attr">name</span>: <span class="string">'poetries'</span>])</span><br></pre></td></tr></table></figure>
<blockquote>
<p>json数据类型和python对比</p>
</blockquote>
<table>
<thead>
<tr>
<th>JSON</th>
<th>python</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>object</code></td>
<td><code>dict</code></td>
</tr>
<tr>
<td><code>array</code></td>
<td><code>list</code></td>
</tr>
<tr>
<td><code>string</code></td>
<td><code>str</code></td>
</tr>
<tr>
<td><code>number</code></td>
<td><code>int</code></td>
</tr>
<tr>
<td><code>number</code></td>
<td><code>float</code></td>
</tr>
<tr>
<td><code>true</code></td>
<td><code>True</code></td>
</tr>
<tr>
<td><code>false</code></td>
<td><code>False</code></td>
</tr>
<tr>
<td><code>null</code></td>
<td><code>None</code></td>
</tr>
</tbody>
</table>
<h2 id="十六、爬虫"><a href="#十六、爬虫" class="headerlink" title="十六、爬虫"></a>十六、爬虫</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/12/111.png" alt="模块"></p>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="string">''' </span></span><br><span class="line"><span class="string">原生爬虫: 分页爬取我的博客文章列表</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> urllib <span class="keyword">import</span> request</span><br><span class="line"><span class="keyword">import</span> re,json,os</span><br><span class="line"></span><br><span class="line">baseUrl = <span class="string">'http://blog.poetries.top'</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Spider</span><span class="params">()</span>:</span></span><br><span class="line">  url = baseUrl + <span class="string">'/archives/'</span></span><br><span class="line">  pattern = <span class="string">'&lt;a class="post-title" href="(.*)"&gt;([\w]*?)&lt;/a&gt;'</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,page=<span class="number">1</span>)</span>:</span></span><br><span class="line">    self.page = page </span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__fetch_content</span><span class="params">(self)</span>:</span></span><br><span class="line">    url = Spider.url</span><br><span class="line">    <span class="keyword">if</span> self.page != <span class="number">1</span>: </span><br><span class="line">      url = Spider.url + <span class="string">'page/'</span> + str(self.page)</span><br><span class="line"></span><br><span class="line">    r = request.urlopen(url)</span><br><span class="line">    <span class="comment">#bytes</span></span><br><span class="line">    htmls = str(r.read(), encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">    <span class="keyword">return</span> htmls</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">_analyse</span><span class="params">(self, htmls)</span>:</span></span><br><span class="line">    res = re.findall(Spider.pattern, htmls)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">    htmls = self.__fetch_content()</span><br><span class="line">    <span class="keyword">return</span> self._analyse(htmls)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 分页获取所有文章标题</span></span><br><span class="line">result = [] <span class="comment"># 保存多页数据 [[],[],[]]</span></span><br><span class="line"><span class="keyword">for</span> page <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">15</span>):</span><br><span class="line">  print(<span class="string">'开始趴取，第(%d/%d)页文章.......'</span>%(page,<span class="number">14</span>))</span><br><span class="line">  spider = Spider(page)</span><br><span class="line">  res = spider.start()</span><br><span class="line">  result.append(res)</span><br><span class="line">  <span class="keyword">if</span> page == <span class="number">14</span>:</span><br><span class="line">    print(<span class="string">'所有页面已趴取完...'</span>)</span><br><span class="line"></span><br><span class="line">data = [] <span class="comment"># 处理后的数据</span></span><br><span class="line"><span class="keyword">if</span> len(result) != <span class="number">0</span>:</span><br><span class="line">  <span class="keyword">for</span> i <span class="keyword">in</span> result:</span><br><span class="line">    res = list(map(<span class="keyword">lambda</span> item: &#123;</span><br><span class="line">        <span class="string">'url'</span>: baseUrl + item[<span class="number">0</span>],</span><br><span class="line">        <span class="string">'title'</span>: item[<span class="number">1</span>]</span><br><span class="line">      &#125;,i))</span><br><span class="line">    <span class="comment"># 合并两个数组 [] + []</span></span><br><span class="line">    data += res</span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 保存到当前文件夹</span></span><br><span class="line">  <span class="keyword">with</span> open(os.path.dirname(__file__) + <span class="string">'/blog.text'</span>,<span class="string">'w'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(json.dumps(data))</span><br><span class="line"></span><br><span class="line">print(data)</span><br></pre></td></tr></table></figure>
<h2 id="十七、常用库"><a href="#十七、常用库" class="headerlink" title="十七、常用库"></a>十七、常用库</h2><h3 id="datetime库"><a href="#datetime库" class="headerlink" title="datetime库"></a>datetime库</h3><blockquote>
<p><code>datetime</code>库可以从系统中获得时间，并以用户选择的格式输出</p>
</blockquote>
<blockquote>
<ul>
<li><code>datetime</code>库以格林威治时间为基础，每天由<code>3600*24</code>秒精准定义</li>
<li><code>datetime</code>库以类的方式提供多种日期和时间</li>
</ul>
</blockquote>
<ul>
<li><code>datetime.date</code>：日期表示类，坑人表示年、月、日等。</li>
<li><code>datetime.time</code>：时间表示类，可表示小时、分钟、秒、毫秒等。</li>
<li><code>datetime.datetime</code>：日期和时间表示类，功能覆盖date和time类。</li>
<li><code>datetime.timedelta</code>：与时间间隔有关的类。</li>
<li><code>datetime.tzinfo</code>：与时区有关的信息表示类。</li>
</ul>
<p><strong>datetime库解析</strong></p>
<ol>
<li><code>datetime.now()</code>：返回一个<code>datetime</code>类型，表示当前日期和时间，精确到毫秒</li>
</ol>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt;<span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line">&gt;&gt;&gt;now=datetime.now()</span><br><span class="line">&gt;&gt;&gt;now</span><br><span class="line">datetime.datetime(<span class="number">2018</span>, <span class="number">5</span>, <span class="number">13</span>, <span class="number">16</span>, <span class="number">49</span>, <span class="number">38</span>, <span class="number">627464</span>)</span><br></pre></td></tr></table></figure>
<ol start="2">
<li><code>datetime.utcnow()</code>：返回一个<code>datetime</code>类型，表示当前日期和时间的<code>UTC</code>（世界标准时间）表示，精确到毫秒</li>
</ol>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt;<span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line">&gt;&gt;&gt;utcnow=datetime.now()</span><br><span class="line">&gt;&gt;&gt;utcnow</span><br><span class="line">datetime.datetime(<span class="number">2018</span>, <span class="number">5</span>, <span class="number">13</span>, <span class="number">8</span>, <span class="number">53</span>, <span class="number">59</span>, <span class="number">788612</span>)</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>直接使用<code>datetime()</code>构造一个日期和时间对象：</li>
</ol>
<blockquote>
<p>datetime(Y,M,D,hour=0,minute=0,second=0,microsecond=0)</p>
</blockquote>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt;some=datetime(<span class="number">2018</span>,<span class="number">5</span>,<span class="number">13</span>,<span class="number">17</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>)</span><br><span class="line">&gt;&gt;&gt;some</span><br><span class="line">datetime.datetime(<span class="number">2018</span>, <span class="number">5</span>, <span class="number">13</span>, <span class="number">17</span>, <span class="number">0</span>)</span><br></pre></td></tr></table></figure>
<p><strong>datetime类的常用属性</strong></p>
<table>
<thead>
<tr>
<th>属性</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>some.min</code></td>
<td>固定返回<code>datetime</code>的最小时间对象，<code>datetime(1,1,1,0,0)</code></td>
</tr>
<tr>
<td><code>some.max</code></td>
<td>固定返回datetime的最大时间对象，<code>datetime(9999,12,31,23,59,59,999999)</code></td>
</tr>
<tr>
<td><code>some.year</code></td>
<td>返回<code>some</code>包含的年份</td>
</tr>
<tr>
<td><code>some.month</code></td>
<td>返回<code>some</code>包含的月份</td>
</tr>
<tr>
<td><code>some.day</code></td>
<td>返回<code>some</code>包含的日期</td>
</tr>
<tr>
<td><code>some.hour</code></td>
<td>返回<code>some</code>包含的小时</td>
</tr>
<tr>
<td><code>some.minute</code></td>
<td>返回<code>some</code>包含的分钟</td>
</tr>
<tr>
<td><code>some.second</code></td>
<td>返回<code>some</code>包含的秒钟</td>
</tr>
<tr>
<td><code>some.microsecond</code></td>
<td>返回<code>some</code>包含的毫秒</td>
</tr>
</tbody>
</table>
<p><strong>datetime类的常用时间格式化方法</strong></p>
<p>|属性|    描述|<br>|<code>some.isofomat()</code>    |采用<code>ISO8601</code>标准显示时间|<br>|<code>some.isoweekday()</code>    |根据日期计算星期|<br>|<code>some.strftime()</code>    |根据格式化字符串<code>format</code>进行格式显示的方法|</p>
<p><strong>strftime()方法用于输出特定格式时间</strong></p>
<table>
<thead>
<tr>
<th>格式化字符串</th>
<th>对象</th>
<th>取值范围</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>%Y</code></td>
<td>年</td>
<td><code>0001~9999</code></td>
</tr>
<tr>
<td><code>%m</code></td>
<td>月</td>
<td><code>1~12</code></td>
</tr>
<tr>
<td><code>%B</code></td>
<td>月名</td>
<td><code>January~December</code></td>
</tr>
<tr>
<td><code>%b</code></td>
<td>月名缩写</td>
<td><code>Jan~Dec</code></td>
</tr>
<tr>
<td><code>%d</code></td>
<td>日期</td>
<td><code>01~31</code></td>
</tr>
<tr>
<td><code>%A</code></td>
<td>星期</td>
<td><code>Monday~Sunday</code></td>
</tr>
<tr>
<td><code>%a</code></td>
<td>星期缩写</td>
<td><code>Mon~Sum</code></td>
</tr>
<tr>
<td><code>%H</code></td>
<td>小时（<code>24h</code>制）</td>
<td><code>00~23</code></td>
</tr>
<tr>
<td><code>%I</code></td>
<td>小时（<code>12h</code>制）</td>
<td><code>01~12</code></td>
</tr>
<tr>
<td><code>%p</code></td>
<td>上、下午</td>
<td><code>AM/PM</code></td>
</tr>
<tr>
<td><code>%M</code></td>
<td>分钟</td>
<td><code>00~59</code></td>
</tr>
<tr>
<td><code>%S</code></td>
<td>秒</td>
<td><code>00~59</code></td>
</tr>
</tbody>
</table>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt;some=datetime(<span class="number">2018</span>,<span class="number">5</span>,<span class="number">13</span>,<span class="number">17</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>)</span><br><span class="line">&gt;&gt;&gt;some.strftime(<span class="string">"%Y年%m月%d日，%H时%M分%S秒"</span>)</span><br><span class="line"><span class="string">'2018年05月13日，17时00分00秒'</span></span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt;print(<span class="string">'今天是&#123;0:%Y&#125;年&#123;0:%m&#125;月&#123;0:%d&#125;日'</span>.format(some))</span><br><span class="line">今天是<span class="number">2018</span>年<span class="number">05</span>月<span class="number">13</span>日</span><br></pre></td></tr></table></figure>
<h3 id="random库"><a href="#random库" class="headerlink" title="random库"></a>random库</h3><blockquote>
<p>random库采用梅森旋转算法生成伪随机数序列，可用于除随机性要求更高的加解密算法外的大多数工程应用</p>
</blockquote>
<ul>
<li><code>Python</code>内置的<code>random</code>库主要用于产生各种分布的伪随机数序列</li>
<li><code>random</code>库提供<code>9</code>个常用函数</li>
</ul>
<table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>seed(a=None)</code></td>
<td>初始化随机数种子，默认值为当前系统时间</td>
</tr>
<tr>
<td><code>random()</code></td>
<td>生成一个<code>[0.0,1.0]</code>之间的随机小数</td>
</tr>
<tr>
<td><code>randint(a,b)</code></td>
<td>生成一个<code>[a,b]</code>之间的整数</td>
</tr>
<tr>
<td><code>getrandbits(k)</code></td>
<td>生成一个<code>k</code>比特长度的随机整数</td>
</tr>
<tr>
<td><code>randrange(start,stop[,step])</code></td>
<td>生成一个[start,stop]之间以<code>step</code>为步数的随机整数</td>
</tr>
<tr>
<td><code>uniform(a,b)</code></td>
<td>生成一个<code>[a,b]</code>之间的随机小数</td>
</tr>
<tr>
<td><code>choice(seq)</code></td>
<td>从序列类型，例如列表中随机返回一个元素</td>
</tr>
<tr>
<td><code>shuffle(seq)</code></td>
<td>将序列类型中的元素随机排列，返回打乱后的序列</td>
</tr>
<tr>
<td><code>sample(pok,k)</code></td>
<td>从<code>pop</code>类型中随机选取<code>k</code>个元素，以列表类型返回</td>
</tr>
</tbody>
</table>
<blockquote>
<p>生成随机数之前可通过<code>seed()</code>函数指定随机数种子，随机数种子一般是一个整数，只要种子相同，每次生成的随机数序列也相同</p>
</blockquote>
<h2 id="十八、技巧"><a href="#十八、技巧" class="headerlink" title="十八、技巧"></a>十八、技巧</h2><p><strong>查看命令信息</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 例如</span></span><br><span class="line">help(filter)</span><br></pre></td></tr></table></figure>
<p><strong>列表中取出符合条件的元素</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 取出大于5的元素</span></span><br><span class="line"></span><br><span class="line">arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>]</span><br><span class="line"></span><br><span class="line">arr1 = filter(lambda x: x&gt;<span class="number">5</span>, arr)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 转化为列表</span></span><br><span class="line">list(arr1)</span><br></pre></td></tr></table></figure>
<p><strong>列表推导式</strong></p>
<blockquote>
<p>代替for和if嵌套循环。最常用的方式</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// for循环列子</span></span><br><span class="line">list = []</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line"> <span class="keyword">if</span> x % <span class="number">2</span> == <span class="number">0</span>:</span><br><span class="line">    list.append(x*x)</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 等价于上面写法</span></span><br><span class="line">[x*x <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">10</span>) <span class="keyword">if</span> x%<span class="number">2</span> == <span class="number">0</span>]</span><br></pre></td></tr></table></figure>
<p><strong>字典推导式</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 一般写法</span></span><br><span class="line">d = &#123;&#125;</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="string">'xxx'</span>:</span><br><span class="line">  d[i] = i</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 字典推导写法</span></span><br><span class="line">&#123;<span class="attr">i</span>:i <span class="keyword">for</span> i <span class="keyword">in</span> <span class="string">'xxx'</span>&#125;</span><br></pre></td></tr></table></figure>
<p><strong>文件读取</strong></p>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="comment"># f = open('test.txt',encoding='utf-8')</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># data = f.readlines()</span></span><br><span class="line"><span class="comment"># for line in data:</span></span><br><span class="line"><span class="comment">#   print(line.strip('\n'))</span></span><br><span class="line">  </span><br><span class="line"><span class="comment"># f.close()</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 推荐用with处理</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'test.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">  <span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">    print(line.strip(<span class="string">'\n'</span>))</span><br></pre></td></tr></table></figure>
<p><strong>函数作用域</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">def test():</span><br><span class="line">    global a <span class="comment">// 定义一个全局变量</span></span><br></pre></td></tr></table></figure>
<p><strong>装饰器</strong></p>
<blockquote>
<p>本质是返回一个闭包</p>
</blockquote>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">log</span><span class="params">(func)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">()</span>:</span></span><br><span class="line">        print(<span class="string">'start'</span>)</span><br><span class="line">        func()</span><br><span class="line">        print(<span class="string">'end'</span>)</span><br><span class="line">    <span class="keyword">return</span> wrapper</span><br><span class="line">    </span><br><span class="line"><span class="meta">@log</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">()</span>:</span></span><br><span class="line">    print(<span class="string">'测试'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>交换两个变量</strong></p>
<figure class="highlight py"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = <span class="number">10</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = <span class="number">20</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x,y = y,x</span><br></pre></td></tr></table></figure>
<h2 id="十九、Python知识体系"><a href="#十九、Python知识体系" class="headerlink" title="十九、Python知识体系"></a>十九、Python知识体系</h2><p><img src="https://poetries1.gitee.io/img-repo/2019/12/181.png" alt="Python知识体系"></p>
<h2 id="二十、更多参考"><a href="#二十、更多参考" class="headerlink" title="二十、更多参考"></a>二十、更多参考</h2><ul>
<li><a href="https://www.liaoxuefeng.com/wiki/1016959663602400" target="_blank" rel="noopener">廖雪峰python3教程</a></li>
<li><a href="https://jupyter.org/" target="_blank" rel="noopener">Jupyter Notebook</a></li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/11/17/es6-review-summary/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/12/11/python-base-2/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
